interval_0 = 500
interval_1 = 500

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-a",type=int,default=interval_0)
parser.add_argument("-b",type=int,default=interval_1)

args = parser.parse_args()
interval_0 = args.a
interval_1 = args.b

import time
import threading
signal = threading.Event()
signal.clear()
def sleep_ms(duration):
    time.sleep(duration/1000)

from twisted.internet import protocol, reactor
# import sys
# import multiprocessing
# password is a must here. not kidding.
import sys
class MyPP(protocol.ProcessProtocol):
    global signal
    def connectionMade(self):
        CM = lambda: print("ConnectionMade")
        reactor.callLater(1.0, CM)

    def check_hint(self,target):
        hint = "COMMANDS"
        if type(target) == bytes:
            target = str(target)
        return hint in target

    def check_content(self,content):
        if not signal.is_set():
            if self.check_hint(content):
                signal.set()

    def write(self, a):
        # binary.
        assert type(a) == bytes
        self.transport.write(a)

    def processExited(self, reason):
        print("processExited, status %s" % (reason.value.exitCode,))

    def merge_raw_output(self, data):
        sys.stdout.buffer.write(data)
        sys.stdout.buffer.flush()
        # you would print it out immediately.

    def outReceived(self, data):
        self.check_content(data)
#        print(data)
        self.merge_raw_output(data)
        # we will merge everything

    def errReceived(self, data):
        self.check_content(data)
        self.merge_raw_output(data)
        #print("errReceived!", data)

if __name__ == "__main__":
    # multiprocessing.freeze_support()
    # while mainthread is alive... -> do the thing.
    pp = MyPP()
    wait_timeout = 5
    # command = ['screen', '-x']
    # wait for the signal.
#    command = ['bash']
    command="bash demo_stop_cont_launcher.sh"  # be exact this time.
    command = command.split(" ")
    # does this work in WINDOWS?
    def theFunc(a):
        a.run()
    reactor.spawnProcess(pp, command[0], command, {'TERM': 'xterm'}, usePTY=False)
    # print("{MIDDLE}")
    p =threading.Thread(target=theFunc,args=(reactor,))
    p.setDaemon(True) # the whole shit.
    # print("{AHEAD}")
    # start after the set.
    # somehow.
    # all dead here. not even better than JS.
    p.start() # not RUN!
    # what the heck?
        # with TIMESTAMP.
    try:
        # print("{OF}")
        signal.wait(timeout=wait_timeout)
        while True:
            pp.write(b"p\n")
            sleep_ms(interval_0)
            pp.write(b"r\n")
            sleep_ms(interval_1)
    except:
        print("waitiing has timed out and we will kill it shortly.")
    print("__EOL__")
        # sys.exit()
    exit()
    # it works.
    # how to terminate? pid?
    # p.terminate()
    # must be thread?
# do we need a separate process?
# this is running fine.
# but how to communicate?
# somehow worked.
